package top.superflow.version.db.jpa

import javax.persistence.{Column, Entity, Index}
import org.apache.commons.lang3.StringUtils
import top.superflow.exception.RequestUnsupportedException
import top.superflow.log.Loggable
import top.superflow.version.db.EntityVersion

class JpaEntityVersion (originalEntity : Any) extends EntityVersion 
with Loggable {
  notNull(originalEntity, "The originalEntity should not be nul.")
  
  originalEntity match {
    case entityClass : Class[_] => {
      val entity = entityClass.getAnnotation(classOf[Entity])
      
      val className = entityClass.getSimpleName
      val finalName = if(StringUtils.isEmpty(entity.name)) className else entity.name()
      
      this.name.compareAndSet(this.name.get, finalName)
      
      for (field <- entityClass.getDeclaredFields) {
        if (field.isAnnotationPresent(classOf[Column])) {
          
          val fieldVersion = new JpaFieldVersion(field)
          this.fields += (fieldVersion.name.get -> fieldVersion)
          
          val fieldIndex = field.getDeclaredAnnotation(classOf[Index])
          addIndex(fieldIndex)
          
        }else if(field.isAccessible()){
          logger.warn("The current column {} for class {} has not been annotated with javax.persistence.Column", field.getName, entityClass.getName )
        }
      }
      
      val classIndex = entityClass.getAnnotation(classOf[Index])
      addIndex(classIndex)
    }
    
    case _ => {
      throw new RequestUnsupportedException("Only javax.persistence.Entity is supported")
    }
  }
  
  def getId : String = {
    this.name.get
  }
  
  def addIndex(index : Index){
    if (index != null) {
      val indexVersion = new JpaIndexVersion(index)
      this.indexes += (indexVersion.name.get -> indexVersion)
    }
  }

}